// pages/me/pages/personalInfo.js
import { input } from '../../../utils/tools'
import { formatTime2 } from '../../../utils/util'
const {
  http
} = require("../../../utils/apiutils")

//获取指定的Canvas
// var radCtx = wx.createCanvasContext("radarCanvas", this)
var radCtx;
var numCount = 5;  //元素个数
var numSlot = 1;  //一条线上的总节点数
var mW = 165;  //Canvas的宽度
var mCenter = mW / 2; //中心点
var mAngle = Math.PI * 2 / numCount; //角度
var mRadius = mCenter - 45; //半径(减去的值用于给绘制的文本留空间)


Page({

  /**
   * 页面的初始数据
   */
  data: {
    chanelArray1: [["沟通能力", 0], ["生存能力", 0], ["经济能力", 0], ["创造能力", 0], ["信息能力", 0]],
    chanelArray2: [["沟通能力", 0], ["生存能力", 0], ["经济能力", 0], ["创造能力", 0], ["信息能力", 0]],
    active: 0,
    radarImg: '',
    popShow: false,
    record: '',
    talentPhone: '',
    userId: '',
    labelArr: [],
    talentInfo: {},
    showPhone: false,
    showText: false,
    CommunicationInfo: {},
    dataList: [],
    hasMore: true,
    loading: false,
    paramsList: {
      talentId: '',
      pageNo: 1,
      pagSize: 10,
    },


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    radCtx = wx.createCanvasContext("radarCanvas", this)
    radCtx.save()
    radCtx.setFillStyle('white')
    radCtx.fillRect(0, 0, 165, 180);//画出矩形白色背景
    radCtx.restore()
    this.setData({
      userId: options.id - 0
      // userId: 9,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      radarImg: ''
    })
    this.getDescribe({ id: this.data.userId })
    this.getUserPortrait({ userId: this.data.userId })
    this.getLabelText({ userId: this.data.userId })
    setTimeout(() => {
      this.getCommunicationRecord({ talentId: this.data.talentInfo.talentId })
      this.setData({
        ['paramsList.talentId']: this.data.talentInfo.talentId
      })
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      labelArr: [],
      dataList: [],
      hasMore: true,
      loading: false,
      ['paramsList.pageNo']: 1
    })


  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // ***************雷达图开始*********************
  drawRadar: function () {
    var sourceData1 = this.data.chanelArray1
    var sourceData2 = this.data.chanelArray2
    wx.showLoading({
      title: '图形绘制中...',
    })
    // this.drawEdge() //画六边形
    this.drawArcEdge() //画圆
    this.drawLinePoint() //绘制连接点
    this.drawRegion(sourceData1, 'rgba(255, 110, 19, 0.5)') //设置数据
    this.drawRegion2(sourceData2, 'rgba(65, 176, 53, 0.5)') //设置数据
    this.drawTextCans(sourceData1) //设置文本数据
    this.drawNumText(sourceData1)//设置文本数字数据
    // this.drawCircle(sourceData1, 'red') //设置节点
    //开始绘制
    setTimeout(() => {
      // radCtx.draw()
      // wx.hideLoading()
      radCtx.draw(false, setTimeout(() => { this.handleCanvarToImg() }, 500))
    }, 1500)
  },
  // 绘制6条边
  drawEdge: function () {
    radCtx.setStrokeStyle("white")
    radCtx.setLineWidth(2)  //设置线宽
    for (var i = 0; i < numSlot; i++) {
      //计算半径
      radCtx.beginPath()
      var rdius = mRadius / numSlot * (i + 1)
      //画6条线段
      for (var j = 0; j < numCount; j++) {
        //坐标
        var x = mCenter + rdius * Math.cos(mAngle * j);
        var y = mCenter + rdius * Math.sin(mAngle * j);
        radCtx.lineTo(x, y);
      }
      radCtx.closePath()
      radCtx.stroke()
    }
  },
  // 第一步：绘制圆，你可以通过修改numSlot的数的大小，来确定绘制几个圆
  drawArcEdge: function () {
    radCtx.setStrokeStyle("#FFD9C2")  //设置线的颜色
    radCtx.setLineWidth(2)  //设置线宽
    for (var i = 0; i < numSlot; i++) {  //需要几个圆就重复几次
      // //计算半径
      radCtx.beginPath()
      var rdius = mRadius / numSlot * (i + 1)  //计算每个圆的半径
      radCtx.arc(mCenter, mCenter, rdius, 0, 2 * Math.PI) //开始画圆
      radCtx.stroke()
    }
  },
  // 绘制连接点
  drawLinePoint: function () {
    radCtx.beginPath();
    for (var k = 0; k < numCount; k++) {
      var x = mCenter + mRadius * Math.cos(mAngle * k);
      var y = mCenter + mRadius * Math.sin(mAngle * k);

      radCtx.moveTo(mCenter, mCenter);
      radCtx.lineTo(x, y);
    }
    radCtx.closePath();
    radCtx.stroke();
  },
  //绘制数据区域(数据和填充颜色)
  drawRegion: function (mData, color) {
    radCtx.beginPath();
    for (var m = 0; m < numCount; m++) {
      var x = mCenter + mRadius * Math.cos(mAngle * m) * mData[m][1] / 100;
      var y = mCenter + mRadius * Math.sin(mAngle * m) * mData[m][1] / 100;

      radCtx.lineTo(x, y);
    }
    radCtx.closePath();
    radCtx.setFillStyle(color)
    radCtx.fill();
  },
  //绘制数据区域2平均分(数据和填充颜色)
  drawRegion2: function (mData, color) {
    radCtx.beginPath();
    for (var m = 0; m < numCount; m++) {
      var x = mCenter + mRadius * Math.cos(mAngle * m) * mData[m][1] / 100;
      var y = mCenter + mRadius * Math.sin(mAngle * m) * mData[m][1] / 100;

      radCtx.lineTo(x, y);
    }
    radCtx.closePath();
    radCtx.setFillStyle(color)
    radCtx.fill();
  },


  //绘制文字
  drawTextCans: function (mData) {
    radCtx.setFillStyle("#999999")
    radCtx.setFontSize(10) //设置字体
    for (var n = 0; n < numCount; n++) {
      var x = mCenter + mRadius * Math.cos(mAngle * n);
      var y = mCenter + mRadius * Math.sin(mAngle * n);
      // radCtx.fillText(mData[n][0], x, y);
      //通过不同的位置，调整文本的显示位置
      // if (mAngle * n >= 0 && mAngle * n <= Math.PI / 2) {
      //   console.log('111111',mData[n][0])
      //   radCtx.fillText(mData[n][0], x + 10, y + 10);
      // } else if (mAngle * n > Math.PI / 2 && mAngle * n <= Math.PI) {
      //   console.log('22222',mData[n][0])
      //   radCtx.fillText(mData[n][0], x - radCtx.measureText(mData[n][0]).width - 7, y + 5);
      // } else if (mAngle * n > Math.PI && mAngle * n <= Math.PI * 3 / 2) {
      //   console.log('33333',mData[n][0])
      //   radCtx.fillText(mData[n][0], x - radCtx.measureText(mData[n][0]).width - 5, y);
      // } else {
      //   console.log('44444',mData[n][0])
      //   radCtx.fillText(mData[n][0], x + 4, y - 5);
      // }
      if (n == 0) {
        radCtx.fillText(mData[n][0], x + 3, y + 10);
      } else if (n == 1) {
        radCtx.fillText(mData[n][0], x - 5, y + 30);
      } else if (n == 2) {
        radCtx.fillText(mData[n][0], x - 40, y + 25);
      } else if (n == 3) {
        radCtx.fillText(mData[n][0], x - 47, y + 5);
      } else if (n == 4) {
        radCtx.fillText(mData[n][0], x - 10, y - 10);
      }

    }
  },
  // 绘制数字
  drawNumText: function (mData) {
    radCtx.setFillStyle("#41B035")
    radCtx.setFontSize(10) //设置字体
    for (var n = 0; n < numCount; n++) {
      var x = mCenter + mRadius * Math.cos(mAngle * n);
      var y = mCenter + mRadius * Math.sin(mAngle * n);
      if (n == 0) {
        radCtx.fillText(mData[n][1], x + 17, y - 8);
      } else if (n == 1) {
        radCtx.fillText(mData[n][1], x + 10, y + 15);
      } else if (n == 2) {
        radCtx.fillText(mData[n][1], x - 26, y + 5);
      } else if (n == 3) {
        radCtx.fillText(mData[n][1], x - 30, y - 15);
      } else if (n == 4) {
        radCtx.fillText(mData[n][1], x + 5, y - 25);
      }

    }
  },
  //画点
  drawCircle: function (mData, color) {
    var r = 3; //设置节点小圆点的半径
    for (var i = 0; i < numCount; i++) {
      var x = mCenter + mRadius * Math.cos(mAngle * i) * mData[i][1] / 100;
      var y = mCenter + mRadius * Math.sin(mAngle * i) * mData[i][1] / 100;

      radCtx.beginPath();
      radCtx.arc(x, y, r, 0, Math.PI * 2);
      radCtx.fillStyle = color;
      radCtx.fill();
    }
  },
  // 雷达图层级太高，转换为图片
  handleCanvarToImg() {
    var that = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 165,
      height: 180,
      destWidth: 495,
      destHeight: 540,
      fileType: 'jpg',
      quality: 1,
      canvasId: 'radarCanvas',
      success: function (res) {
        wx.hideLoading()
        // console.log('res', res)
        that.setData({
          radarImg: res.tempFilePath,
        });
      },
      complete: function (err) {
        wx.hideLoading()
        // console.log('err', err)
      }
    }, that);
  },
  // *******************雷达图结束**************************

  // 获取用户信息
  getDescribe(params) {
    http.getDescribe(params, res => {
      if (res.status == 200) {
        this.setData({
          talentInfo: res.obj
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, err => { })
  },
  // 获取雷达图能力数据
  getUserPortrait(params) {
    http.userPortrait(params, res => {
      if (res.status == 200) {
        if (res.obj.myScore) {
          this.setData({
            chanelArray1:
              [['沟通能力', res.obj.myScore.expression ? res.obj.myScore.expression : 0],
              ['健康指数', res.obj.myScore.other ? res.obj.myScore.other : 0],
              ['专业技能', res.obj.myScore.professional ? res.obj.myScore.professional : 0],
              ['理解能力', res.obj.myScore.grasp ? res.obj.myScore.grasp : 0],
              ['学习能力', res.obj.myScore.opretion ? res.obj.myScore.opretion : 0]]
          })
        }
        if (res.obj.avgScore) {
          this.setData({
            chanelArray2:
              [['沟通能力平均分', res.obj.avgScore.expression ? res.obj.avgScore.expression : 0],
              ['健康指数平均分', res.obj.avgScore.other ? res.obj.avgScore.other : 0],
              ['专业技能平均分', res.obj.avgScore.professional ? res.obj.avgScore.professional : 0],
              ['理解能力平均分', res.obj.avgScore.grasp ? res.obj.avgScore.grasp : 0],
              ['学习能力平均分', res.obj.avgScore.opretion ? res.obj.avgScore.opretion : 0]]
          })
        }
        this.drawRadar()
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, err => { })
  },
  // 获取用户标签
  getLabelText(params) {
    http.getLabelText(params, res => {
      if (res.status == 200) {
        this.setData({
          labelArr: res.obj
        })
      }
    }, err => { })
  },
  // 标签页切换
  onTabChange(e) {
    this.setData({
      active: e.detail.index,
      dataList: [],
      hasMore: true,
      loading: false,
      ['paramsList.pageNo']: 1,
    })
    if (this.data.active == 1) {
      this.getBrowseRecord(this.data.paramsList)
    } else if (this.data.active == 2) {
      this.getWorkRecord(this.data.paramsList)
    }
  },
  toShezhi() {
    wx.navigateTo({
      url: '/pages/me/portrait/portrait?userId=' + this.data.userId,
    })
  },
  openPop(e) {
    if (e.currentTarget.dataset.type == 1) {
      this.setData({
        showPhone: true,
        showText: false,
        popShow: true,
      })
    } else if (e.currentTarget.dataset.type == 2) {
      this.setData({
        showPhone: false,
        showText: true,
        popShow: true,
      })
    }
  },
  onPopClose() {
    this.setData({
      popShow: false,
    })
  },
  input(event) {
    input.bind(this)(event)
  },
  cancel() {
    this.onPopClose()
    this.setData({
      record: '',
      talentPhone: ''
    })
  },
  confirm(e) {
    let params = {}
    if (e.currentTarget.dataset.index == 1) {
      params = {
        id: this.data.userId,
        record: this.data.record
      }
      if (!params.record) {
        wx.showToast({
          title: '备注不能为空',
          icon: 'none'
        })
        return
      }
    } else if (e.currentTarget.dataset.index == 2) {
      params = {
        id: this.data.userId,
        talentPhone: this.data.talentPhone
      }
      if (!params.talentPhone) {
        wx.showToast({
          title: '手机号不能为空',
          icon: 'none'
        })
        return
      }
    }

    http.saveDescribe(params, res => {
      if (res.status == 200) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        this.setData({
          record: '',
          talentPhone: ''
        })
        this.onPopClose()
        if (e.currentTarget.dataset.index == 1) {
          this.getCommunicationRecord({ talentId: this.data.talentInfo.talentId })
        } else if (e.currentTarget.dataset.index == 2) {
          this.getDescribe({ id: this.data.userId })
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, err => { })
  },
  onCall() {
    wx.makePhoneCall({
      phoneNumber: this.data.talentInfo.talentPhone,
    })
  },
  // 获取沟通记录
  getCommunicationRecord(params) {
    http.getCommunicationRecord(params, res => {
      if (res.status == 200) {
        if (res.obj) {
          res.obj.create_time = formatTime2(res.obj.create_time)
        }
        this.setData({
          CommunicationInfo: res.obj
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, err => { })
  },
  // 获取浏览记录
  getBrowseRecord(params) {
    var that = this
    that.data.loading = true;
    http.getBrowseRecord(params, res => {
      if (res.status == 200) {
        if (res.obj&&res.obj.records.length > 0) {
          that.setData({
            dataList: [...that.data.dataList, ...res.obj.records],
            loading: false,
            pageNo: that.data.paramsList.pageNo,
            hasMore: res.obj.records.length > 0 ? true : false
          })

        } else {
          that.setData({
            ['paramsList.pageNo']: 1,
            hasMore: false,
            loading: false,

          })
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, erro => {
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    })
  },
  // 获取工作记录
  getWorkRecord(params) {
    var that = this
    that.data.loading = true;
    http.getWorkRecord(params, res => {
      if (res.status == 200) {
        if (res.obj&&res.obj.records.length > 0) {
          that.setData({
            dataList: [...that.data.dataList, ...res.obj.records],
            loading: false,
            pageNo: that.data.paramsList.pageNo,
            hasMore: res.obj.records.length > 0 ? true : false
          })

        } else {
          that.setData({
            ['paramsList.pageNo']: 1,
            hasMore: false,
            loading: false,

          })
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, erro => {
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    })
  },
  // 加载下一页
  getMore() {
    if (this.data.loading) {
      return
    };
    if (!this.data.hasMore) {
      this.setData({
        ['paramsList.pageNo']: 1,
      })
      return
    };
    this.setData({
      ['paramsList.pageNo']: this.data.paramsList.pageNo + 1
    });
    if (this.data.active == 1) {
      this.getBrowseRecord(this.data.paramsList)
    } else if (this.data.active == 2) {
      this.getWorkRecord(this.data.paramsList)
    }
  }

})